import Cfg from './config.js';
import Msg, { Fail } from './message.js';
import Nav from './navigation.js';

const _post = (url,data,success,hook,fail) =>{
	_http('POST',url,data,success,hook,fail);
}

const _get = (url,data,success,hook,fail) =>{
	_http('GET',url,data,success,hook,fail);
}

const _setToken = (token)=>{
	uni.setStorageSync('_TOKEN_',token);
}

const _getToken = () =>{
	return uni.getStorageSync('_TOKEN_') || '';
}

const _delToken = () =>{
	uni.removeStorageSync('_TOKEN_');
}

const _setUserid = (userid)=>{
	uni.setStorageSync('_USERID_',userid);
}

const _getUserid = () =>{
	return uni.getStorageSync('_USERID_') || '';
}

const _delUserid = () =>{
	uni.removeStorageSync('_USERID_');
}

//网络请求
const _http = (type,url,data,success,hook,fail)=>{
	let that = this;
	uni.getNetworkType({
		success(e) {
			if(e.networkType == 'none'){
				uni.showToast({
					title: 'Network anomalies, please try again later',
					icon:'none',
					duration:3000
				})
				return;
			}else{
				
				
				let token = _getToken();	
				let lang = uni.getStorageSync('_language');
				let userid = uni.getStorageSync('_USERID_');
				
				data = Object.assign(data,{
					token: token,
					lang:lang 
				});
				uni.showLoading();
				
				uni.request({
					url:  url,
					data:data,		
					dataType:"json",
					method:type,		
					header:{
						'content-type':'application/x-www-form-urlencoded',
						// 'lang':lang,
						'Authorization':token,
					},
					success(res){
						setTimeout(function(){uni.hideLoading()},300)
						if (res.data.code == 401) {
							Msg.Fail(res.data.msg);
							_delToken()
							Nav._to({url:'/pages/public/login',type:1});
							return false;
						}
						
						if (res.data.code == 402) {
							Msg.Fail(res.data.msg,function(){
								Nav._to({url:'/pages/personalcenter/cipher'});
							});
							return false;          
						}
						
						if (res.data.code == 403) {
							success && success(res.data);
							return false;
						}
						
						if (res.data.code != 200) {
							Msg.Fail(res.data.msg)
							return false;
						}else{
							success && success(res.data);
						}
					},
					fail(res){
						setTimeout(function(){uni.hideLoading()},300)
						if(hook){
							fail && fail(res.errMsg);
						}else{
							Msg.Fail(res.errMsg);
							fail && fail(res);
						}
					},
					complete(res){
						//complete && complete(res);			
					} 
				})
			}
		}
	})	
}

module.exports = {    
	_get,
	_post,
	_setToken,
	_getToken,
	_delToken,
	_setUserid,
	_getUserid,
	_delUserid,
}